﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Models;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using StackExchange.Profiling.Internal;

namespace Aioms.Controllers
{
    /// <summary>
    /// 区域接口
    /// </summary>
    [DynamicApiController]
    public class AreaController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public AreaController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 平级区域和搜索
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSearch([FromForm] long eid, [FromForm] string content)
        {
            List<Area> areas = await db.Queryable<Area>().Where(a => a.IsDel == 0).Where(a => a.Eid == eid)
                .WhereIF(!string.IsNullOrEmpty(content), a =>  a.Name.Contains(content))
                .ToListAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = areas,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// PC端-安卓端-区域列表
        /// </summary>
        /// <param name="eid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid)
        {
            JArray data = GetAreaTree(eid, 0).Result;
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        [NonAction]
        public async Task<JArray> GetAreaTree(long eid, long pid)
        {
            JArray data = new();
            List<Area> areas = await db.Queryable<Area>().Where(a => a.IsDel == 0).Where(d => d.Eid == eid && d.ParentId == pid).OrderBy(d => d.SortId, OrderByType.Asc).ToListAsync();
            if (areas != null && areas.Count > 0)
            {
                foreach (var area in areas)
                {
                    JObject jo_menu = JObject.FromObject(area);
                    jo_menu.Add("children", GetAreaTree(eid, area.Id).Result);
                    data.Add(jo_menu);
                }
            }
            return data;
        }

        /// <summary>
        /// PC端-安卓端-根据子ID获取所有父ID
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetallparentbychildrenid([FromForm] long eid, [FromForm] long id)
        {
            await GetAllParent(eid, id);

            JObject data = new();
            areas.Reverse();
            data.Add("parent_areas", JArray.FromObject(areas));
            List<Area> children_areas = await db.Queryable<Area>().Where(a => a.IsDel == 0).Where(d => d.Eid == eid && d.ParentId == id).ToListAsync();
            data.Add("children_areas", children_areas == null ? null : JArray.FromObject(children_areas));
            return new JsonResult(new { status = "success", message = "获取所有父类成功", code = 1, data });
        }

        private readonly List<Area> areas = new(); // 所有区域父区域
        [NonAction]
        public async Task GetAllParent(long eid, long id)
        {
            // 查询当前节点信息
            Area area = await db.Queryable<Area>().Where(a => a.IsDel == 0).Where(d => d.Eid == eid && d.Id == id).SingleAsync();
            if (area != null)
            {
                areas.Add(area);
                await GetAllParent(eid, area.ParentId);
            }
        }

        /// <summary>
        /// PC端-安卓端-异步获取子区域
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetchildren([FromForm] long eid, [FromForm] long id)
        {
            List<Area> areas = await db.Queryable<Area>().Where(a => a.IsDel == 0).Where(ae => ae.Eid == eid && ae.ParentId == id).OrderBy("sort_id asc").ToListAsync();
            JArray data = new();
            foreach (var area in areas)
            {
                JObject jo_area = JObject.FromObject(area);
                //int nextleveltotal = await db.Queryable<Area>().Where(a => a.IsDel == 0).Where(ae => ae.Eid == eid && ae.ParentId == area.Id).OrderBy("sort_id asc").CountAsync();
                jo_area.Add("nextleveltotal", area.ChildCount);
                data.Add(jo_area);
            }
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 区域增加
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="area"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSave([FromForm] long eid, [FromForm] Area area)
        {
            Area lastarea = await db.Insertable<Area>(area).ExecuteReturnEntityAsync();
            // 父部门中childcount数量加1
            await db.Updateable<Area>().SetColumns(a => a.ChildCount == a.ChildCount + 1).Where(a => a.Id == area.ParentId).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = lastarea,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDelete([FromForm] long eid, [FromForm] long id, [FromForm] long parentid)
        {
            // 该区域下有子区域不让删除
            Area area = await db.Queryable<Area>().Where(a => a.IsDel == 0).Where(a => a.Eid == eid && a.ParentId == id).SingleAsync();
            if (area != null)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "该区域下拥有子区域，不允许删除",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            int affrows = await db.Updateable<Area>().SetColumns(a => a.IsDel == 1).Where(a => a.Eid == eid && a.Id == id).ExecuteCommandAsync();
            // 父部门中childcount数量减1
            await db.Updateable<Area>().SetColumns(a => a.ChildCount == a.ChildCount - 1).Where(a => a.Id == parentid).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = affrows,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="area"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdate([FromForm] long eid, [FromForm] Area area)
        {
            int affrows = await db.Updateable<Area>(area).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = affrows,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 区域查看
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShow([FromForm] long eid, [FromForm] long id)
        {
            Area area = await db.Queryable<Area>().Where(a => a.IsDel == 0).Where(d => d.Eid == eid && d.Id == id).SingleAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = area,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 拖拽
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="strjsonareas"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDrag([FromForm] long eid, [FromForm] string strjsonareas)
        {
            List<Area> areas = JsonConvert.DeserializeObject<List<Area>>(strjsonareas);
            areas.ForEach(d => d.SortId = areas.IndexOf(d) + 1);
            int affrows = await db.Updateable<Area>(areas).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = affrows,
                Errors = "拖拽更新成功",
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
